﻿Imports System.Data.SqlClient
Imports ADOConnection

Public Class frmChonMatHang
    Public fCallPhieuNX As Form = Nothing ' Bien nay cho biet form hay co dc goi tu form khac ko?
    'Code: Hoang Tuan 
    'Bien nay dung de dem so lan nguoi dung double click de add mat hang moi vao phieu nhap
    'Neu count = 1 thi add mot mat hang duy nhat
    'neu count > 1 thi add nhieu mat hang mot luc
    Dim count As Integer = 0

    Public Sub New(ByVal LoaiMH_Id As String, ByVal loaikho As String, ByVal kho As String)

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        ma_cha = LoaiMH_Id

        ma_loaikho = loaikho
        ma_kho = kho
        dpnx_id = Nothing
        ngay = Now.Date
        Me.Text = "Danh mục mặt hàng ở " + CDoiTuongs.GetNameByMa(enumDOITUONG.KHO, kho)
    End Sub

    Public Sub New(ByVal LoaiMH_Id As String, ByVal dpnxid As Integer, ByVal ngaynx As Date, ByVal loaikho As String, ByVal kho As String)
        'dung khoi tao dm lo hang cho phieu xuat
        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        ma_cha = LoaiMH_Id

        ma_loaikho = loaikho
        ma_kho = kho
        dpnx_id = dpnxid
        ngay = ngaynx
        Me.Text = "Danh mục mặt hàng ở " + CDoiTuongs.GetNameByMa(enumDOITUONG.KHO, kho)
    End Sub

    Private Sub frmChonMatHang_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ' Create columns for the items and subitems.
        lvDMMatHang.Columns.Add("Tên mặt hàng", 178, HorizontalAlignment.Left)
        lvDMMatHang.Columns.Add("Lô hàng", 117, HorizontalAlignment.Left)
        lvDMMatHang.Columns.Add("Hạn SD", 56, HorizontalAlignment.Left)
        lvDMMatHang.Columns.Add("SL Tồn", 59, HorizontalAlignment.Right)
        lvDMMatHang.Columns.Add("Mã mặt hàng", 0, HorizontalAlignment.Center)
        lblSLKH.Visible = False
        txtSLKH.Visible = False
        Init()

        'Tab DM Thuoc
        lvThuoc.Columns.Add("Mã", 130, HorizontalAlignment.Left)
        lvThuoc.Columns.Add("Tên", 300, HorizontalAlignment.Left)
        lvThuoc.Columns.Add("ĐVT", 70, HorizontalAlignment.Left)
        LoadDMLoaiThuoc()
        LoaddsThuoc()
        '
        Panel3.Height = 0
        Panel3.Visible = False
        KhoiTao_tvDMThuoc()
        tvThuoc.Focus()
        tvThuoc.SelectedNode = tvThuoc.Nodes.Item(0)

        lvThuoc.LabelEdit = True
        ' Allow the user to rearrange columns.
        lvThuoc.AllowColumnReorder = True
        ' Select the item and subitems when selection is made.
        lvThuoc.FullRowSelect = True
        ' Display grid lines.
        lvThuoc.GridLines = True
        ' Sort the items in the list in ascending order.
        lvThuoc.Sorting = SortOrder.Ascending
    End Sub

#Region "Old Code"

    '#Region "Tab DM THUOC,TRANG BI, DUNG CU"

    '    'Public bFirst As Boolean = True 'Bien nay dung de cho biet form dc goi lan dau tien?

    '    Dim daThuoc As SqlDataAdapter
    '    Dim dsThuoc, dsLoaiThuoc As DataSet

    '    Dim flagthem As Boolean = False
    '    Dim flagsua As Boolean = False

    '    Public ma_cha As String = ""



    '#Region "Load dsThuoc & dsLoaiThuoc"
    '    Public Sub LoadDMLoaiThuoc()
    '        Dim strSQl As String = "select * from tblLoaiThuoc"
    '        dsLoaiThuoc = BaseDB.ExecSql_DataSet(strSQl)
    '    End Sub

    '    Public Sub LoaddsThuoc()
    '        dsThuoc = BaseDB.ExecSql_DataSet("select * from tblDMTHUOC")
    '    End Sub
    '#End Region

    '#Region "tvThuoc"
    '    Public Sub KhoiTao_tvDMThuoc()
    '        'cho chon tat ca cac mat hang
    '        Dim node As TreeNode
    '        node = tvThuoc.Nodes.Add("KHO 706")

    '        ''neu chon Thuoc hoac HoaChat hoac BB thi DM gom T + HC + BB
    '        'Dim node As TreeNode
    '        'node = tvThuoc.Nodes.Add("KHO 706")
    '        'If (ma_cha <> "") Then
    '        '    '"Y0500000000000"
    '        '    Dim strLoc As String
    '        '    If (ma_cha <> "Y0500000000000") And (ma_cha <> "Y0600000000000") And (ma_cha <> "Y0700000000000") Then
    '        '        strLoc = "ma_loaithuoc ='" & ma_cha & "'"
    '        '    Else
    '        '        strLoc = "ma_loaithuoc ='Y0500000000000' or ma_loaithuoc ='Y0600000000000' or ma_loaithuoc ='Y0700000000000'"
    '        '    End If
    '        '    Dim adr() As DataRow
    '        '    adr = dsLoaiThuoc.Tables(0).Select(strLoc)
    '        '    Dim row As DataRow
    '        '    For Each row In adr
    '        '        Dim childNode As TreeNode = node.Nodes.Add(row("ten_loaithuoc"))
    '        '        tvThuoc.SelectedNode = childNode
    '        '    Next
    '        'End If
    '    End Sub

    '    Private Sub tvThuoc_AfterSelect(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs)
    '        'AddChildCurrentNode()
    '        If (tvThuoc.SelectedNode.GetNodeCount(False) = 0) Then
    '            AddChildNode(CLoaiThuocs.GetLoaiThuocByTen(tvThuoc.SelectedNode.Text).MaLoaiThuoc)
    '            'sau khi them ma van khong co nut con 
    '            'y noi la nut la
    '            If (tvThuoc.SelectedNode.GetNodeCount(False) = 0) Then
    '                KhoiTaodtgThuoc(CLoaiThuocs.GetLoaiThuocByTen(tvThuoc.SelectedNode.Text).MaLoaiThuoc)
    '            Else
    '                dtgThuoc.DataSource = Nothing
    '            End If
    '        Else
    '            dtgThuoc.DataSource = Nothing
    '        End If
    '        ''Xac dinh neu la open form lan dau tien thi mo rong cay
    '        'If bFirst Then
    '        '    tvThuoc.ExpandAll()
    '        '    bFirst = False
    '        'End If
    '    End Sub

    '    Public Sub AddChildNode(ByVal macha As String)
    '        Dim strLoc As String
    '        strLoc = "ma_cha ='" & macha & "'"
    '        Dim adr() As DataRow
    '        adr = dsLoaiThuoc.Tables(0).Select(strLoc)
    '        Dim row As DataRow
    '        For Each row In adr
    '            tvThuoc.SelectedNode.Nodes.Add(row("ten_loaithuoc"))
    '        Next
    '    End Sub

    '    Public Sub RefreshCurrentNode()
    '        LoadDMLoaiThuoc()
    '        Dim node As TreeNode
    '        node = tvThuoc.SelectedNode
    '        node.Nodes.Clear()
    '        AddChildNode(CLoaiThuocs.GetLoaiThuocByTen(node.Text).MaLoaiThuoc)
    '    End Sub

    '#End Region

    '#Region "dtgThuoc"
    '    Public Sub KhoiTaodtgThuoc(ByVal loaichaID As String)
    '        Dim dv As DataView = New DataView(dsThuoc.Tables(0))
    '        dv.RowFilter = " MaLoaiThuoc = '" & loaichaID & "'"
    '        dtgThuoc.DataSource = dv
    '        FormatGridStyleThuoc()
    '    End Sub

    '    Public Sub FormatGridStyleThuoc()
    '        With dtgThuoc
    '            'Rename(HeaderText)
    '            With .Columns.Item("mathuoc")
    '                .HeaderText = "Mã Thuốc"
    '                .Width = 100
    '            End With
    '            With .Columns.Item("tenthuoc")
    '                .HeaderText = "Tên Thuốc"
    '                .Width = 300
    '            End With
    '            With .Columns.Item("maloaithuoc")
    '                .HeaderText = ""
    '                .ReadOnly = True
    '                .Visible = False
    '            End With
    '            With .Columns.Item("donvitinh")
    '                .HeaderText = "ĐVT"
    '                .Width = 75
    '            End With
    '        End With
    '    End Sub
    '#End Region

    '#Region "btn Them, Xoa, Sua, Ghi, Huy"
    '    Private Sub btnThem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '        If tvThuoc.SelectedNode.Nodes.Count() = 0 Then
    '            Dim frm As New frmNhapThuoc(CLoaiThuocs.GetLoaiThuocByTen(tvThuoc.SelectedNode.Text).MaLoaiThuoc, True)
    '            frm.fCallVattu = Me
    '            frm.ShowDialog()
    '        End If
    '    End Sub

    '    Private Sub btnSua_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '        If tvThuoc.SelectedNode.Nodes.Count() = 0 Then
    '            Dim frm As New frmNhapThuoc(dtgThuoc.CurrentRow.Cells(0).Value, False)
    '            frm.fCallVattu = Me
    '            frm.ShowDialog()
    '        End If
    '    End Sub

    '    Private Sub btnXoa_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '        If (tvThuoc.SelectedNode.Nodes.Count() = 0) Then
    '            If (MsgBox("Bạn có muốn xóa loại thuốc này không?", MsgBoxStyle.YesNo, "CHÚ Ý")) = MsgBoxResult.Yes Then
    '                Dim mathuoc As String
    '                mathuoc = dtgThuoc.Item(0, dtgThuoc.CurrentCell.RowIndex).Value
    '                CThuocs.DeleteThuoc(CThuocs.GetThuocByMa(mathuoc))
    '                LoaddsThuoc()
    '                KhoiTaodtgThuoc(CLoaiThuocs.GetLoaiThuocByTen(tvThuoc.SelectedNode.Text).MaLoaiThuoc)
    '            End If
    '        End If
    '    End Sub

    '#End Region

    '#Region "function KiemTraThem"
    '    Function KiemTraThem() As Boolean
    '        If (dsThuoc.HasChanges(DataRowState.Modified)) Then
    '            Dim dsChange As DataSet
    '            dsChange = dsThuoc.GetChanges(DataRowState.Modified)
    '            If (dsChange.Tables(0).Rows.Count > 0) Then
    '                MsgBox("Bạn không được thay đổi các mục khác trong khi thêm")
    '                dsThuoc.RejectChanges()
    '                'btnVisible(True)
    '                tvThuoc.Enabled = True
    '                Return False
    '            End If
    '        End If

    '        Dim mathuoc, tenthuoc, donvitinh As Object
    '        mathuoc = dtgThuoc.Item(0, dtgThuoc.RowCount - 1).Value 'dsThuoc.Tables(0).Rows(dsThuoc.Tables(0).Rows.Count - 1).Item(0)
    '        tenthuoc = dtgThuoc.Item(1, dtgThuoc.RowCount - 1).Value 'dsThuoc.Tables(0).Rows(dsThuoc.Tables(0).Rows.Count - 1).Item(1)
    '        donvitinh = dtgThuoc.Item(4, dtgThuoc.RowCount - 1).Value 'dsThuoc.Tables(0).Rows(dsThuoc.Tables(0).Rows.Count - 1).Item(4)
    '        If (mathuoc Is DBNull.Value) Then
    '            MsgBox("Bạn chưa nhập mã thuốc")
    '            Return False
    '        End If

    '        If (tenthuoc Is DBNull.Value) Then
    '            MsgBox("Bạn chưa nhập tên thuốc")
    '            Return False
    '        End If

    '        If (CStr(mathuoc).Length <> 14) Then
    '            MsgBox("Bạn nhập chiều dài mã chưa đủ 14 ký tự")
    '            Return False
    '        End If

    '        Dim strsql As String
    '        Dim value As Integer

    '        If (Not donvitinh Is DBNull.Value) Then
    '            'trong mot nhom phai khac nhau
    '            'chua xu ly
    '            strsql = "select count(*) from tblDMTHUOC where tenthuoc like N'" & tenthuoc & "'" & _
    '                        " and donvitinh = N'" & donvitinh & "'"
    '            value = BaseDB.ExecSql_DataValue(strsql)
    '            If (value > 0) Then
    '                MsgBox("Đã tồn tại tên thuốc và đơn vị tính này")
    '                Return False
    '            End If
    '        Else
    '            strsql = "select count(*) from tblDMTHUOC where tenthuoc like N'" & tenthuoc & "'"
    '            value = BaseDB.ExecSql_DataValue(strsql)
    '            If (value > 0) Then
    '                MsgBox("Đã tồn tại tên thuốc này")
    '                Return False
    '            End If
    '        End If

    '        Return True
    '    End Function
    '#End Region

    '#Region "btnTim"
    '    Private Sub btnTim_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '        Dim tenthuoc As String
    '        Dim frm As New frmTimKiem
    '        frm.ShowDialog()
    '        tenthuoc = frm.txtGiaTri.Text
    '        If (tenthuoc.Trim <> "") Then
    '            lbxKetQua.Focus()
    '            KhoiTaolbxKetQua(tenthuoc)
    '            If (lbxKetQua.Items.Count <> 0) Then
    '                Panel3.Height = 150
    '                Panel3.Visible = True
    '                lbxKetQua.SelectedIndex = 0
    '                lbxKetQua.Focus()
    '            Else
    '                ShowMessages("Không tìm thấy")
    '            End If
    '        Else
    '            ShowMessages("Bạn chưa nhập tên thuốc cần tìm")
    '        End If
    '    End Sub

    '    Public Sub KhoiTaolbxKetQua(ByVal tenthuoc As String)
    '        Dim aryThuoc As ArrayList
    '        aryThuoc = CThuocs.GetThuocListByTen(tenthuoc)
    '        lbxKetQua.Items.Clear()
    '        For Each objThuoc As CThuoc In aryThuoc
    '            lbxKetQua.Items.Add(objThuoc)
    '        Next
    '    End Sub

    '    Private Sub lbxKetQua_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs)
    '        Try
    '            Dim brText As Brush
    '            If (e.State And DrawItemState.Selected) = DrawItemState.Selected Then
    '                brText = Brushes.White
    '            Else
    '                brText = Brushes.Black
    '            End If
    '            e.DrawBackground()
    '            Dim objThuoc As CThuoc = lbxKetQua.Items(e.Index)  'Me.lstItems.SelectedItem
    '            e.Graphics.DrawString(objThuoc.TenThuoc + " - " + objThuoc.DonViTinh, Me.lbxKetQua.Font, brText, e.Bounds.X + 5, e.Bounds.Y)
    '            e.DrawFocusRectangle()
    '        Catch ex As Exception
    '        Finally
    '        End Try
    '    End Sub

    '    Private Sub lbxKetQua_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
    '        'chon loai thuoc ben treeview loai thuoc
    '        'chon ten thuoc ben dtgDMThuoc

    '        If (lbxKetQua.SelectedIndex <> -1) Then
    '            Dim mathuoc, maloaithuoc As String
    '            Dim objThuoc As CThuoc
    '            objThuoc = CType(lbxKetQua.SelectedItem, CThuoc)
    '            mathuoc = objThuoc.MaThuoc
    '            maloaithuoc = objThuoc.MaLoaiThuoc

    '            'chon loai thuoc ben treeview loaithuoc
    '            ' tao ary chua tat ca cac cha cua loaithuoc dang tim
    '            Dim ary As New ArrayList
    '            Dim objLoaiThuoc As CLoaiThuoc
    '            Dim maloaithuoccha As String
    '            maloaithuoccha = maloaithuoc
    '            While (maloaithuoccha <> "Y0000000000000")
    '                'se bi lap neu tim khong thay
    '                objLoaiThuoc = CLoaiThuocs.GetLoaiThuocByMa(maloaithuoccha)
    '                If (objLoaiThuoc.MaLoaiThuoc Is Nothing) Then
    '                    ShowMessages("Loại thuốc này có mã không phù hợp")
    '                    Exit Sub
    '                End If
    '                ary.Add(objLoaiThuoc)
    '                maloaithuoccha = objLoaiThuoc.MaCha
    '            End While

    '            Dim node As TreeNode
    '            'default value is root
    '            node = tvThuoc.Nodes.Item(0)

    '            For i As Integer = 0 To ary.Count - 1
    '                objLoaiThuoc = ary.Item(ary.Count - i - 1)
    '                ' kiem tra xem node hien hanh co con khong neu chua thi add vao
    '                If (node.GetNodeCount(False) = 0) Then
    '                    'insert 
    '                    Dim aryLoaiThuocCon As ArrayList
    '                    aryLoaiThuocCon = CThuocs.GetThuocListByLoaiChaID(objLoaiThuoc.MaLoaiThuoc)
    '                    For Each obj As CLoaiThuoc In aryLoaiThuocCon
    '                        node.Nodes.Add(obj.TenLoaiThuoc)
    '                    Next
    '                End If
    '                'chon node tiep theo co ten trung voi objloaithuoc
    '                Dim n As TreeNode
    '                For Each n In node.Nodes
    '                    If (n.Text = objLoaiThuoc.TenLoaiThuoc) Then
    '                        node = n
    '                        tvThuoc.SelectedNode = node
    '                        node.ExpandAll()
    '                        Exit For
    '                    End If
    '                Next
    '            Next
    '            tvThuoc.SelectedNode = node
    '            KhoiTaodtgThuoc(maloaithuoc)

    '            'chon ten thuoc ben dtgDMThuoc
    '            dtgThuoc.Focus()
    '            For i As Integer = 0 To dtgThuoc.Rows.Count - 1
    '                If (dtgThuoc.Rows(i).Cells(0).Value.ToString = mathuoc) Then
    '                    'dtgThuoc.SelectedRows(i).Selected = True
    '                    'dtgThuoc.Rows
    '                    dtgThuoc.Rows(i).Selected = True
    '                    'dtgThuoc.Rows(i).= True
    '                    'dtgThuoc.Focus
    '                    'dtgThuoc.Show()
    '                    Exit For
    '                End If
    '            Next
    '            'set focus lai cho lbxKetQua
    '            lbxKetQua.Focus()
    '        End If
    '    End Sub

    '    Private Sub btnCloseKetQua_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '        Panel3.Height = 0
    '        Panel3.Visible = False
    '    End Sub
    '#End Region

    '    Private Sub dtgThuoc_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs)
    '        Try
    '            If fCallPhieuNX IsNot Nothing Then
    '                count += 1
    '                Dim frm As frmPhieuNX = CType(fCallPhieuNX, frmPhieuNX)
    '                frm.AddNhomHang(dtgThuoc.Rows(e.RowIndex).Cells("mathuoc").Value, count)
    '            End If
    '        Catch ex As Exception
    '            ShowMessages("Error: frmVattu dtgThuoc_CellDoubleClick: " + ex.ToString())
    '        End Try
    '    End Sub

    '#Region "Menu Them,Xoa,Sua LoaiThuoc"
    '    Private Sub XóaToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '        'kiem tra co node con hay khong? neu la node cuoi thi kiem tra co thuoc nao ko?
    '        Dim strLoc, maloaithuoc As String
    '        maloaithuoc = CLoaiThuocs.GetLoaiThuocByTen(tvThuoc.SelectedNode.Text).MaLoaiThuoc
    '        strLoc = "ma_cha ='" & maloaithuoc & "'"
    '        Dim adr() As DataRow
    '        adr = dsLoaiThuoc.Tables(0).Select(strLoc)
    '        If (adr.Length <> 0) Then
    '            ShowMessages("Bạn phải xóa các nhóm thuốc con trước khi muốn xóa nhóm thuốc này")
    '            Exit Sub
    '        Else ' day la node la.
    '            'kiem tra xem trong no co thuoc nao hay ko?
    '            strLoc = "MaLoaiThuoc ='" & maloaithuoc & "'"
    '            adr = dsThuoc.Tables(0).Select(strLoc)
    '            If (adr.Length <> 0) Then
    '                ShowMessages("Bạn phải xóa các thuốc con trước khi xóa nhóm thuốc này ")
    '                Exit Sub
    '            End If
    '        End If
    '        CLoaiThuocs.DeleteLoaiThuoc(CLoaiThuocs.GetLoaiThuocByTen(tvThuoc.SelectedNode.Text))
    '        tvThuoc.SelectedNode.Remove()
    '    End Sub

    '    Private Sub ThêmToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '        'cap nhat
    '        Dim frm As New frmNhapLoaiThuoc(CLoaiThuocs.GetLoaiThuocByTen(tvThuoc.SelectedNode.Text))
    '        frm.fCallVattu = Me
    '        frm.ShowDialog()
    '    End Sub

    '    Private Sub SửaToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    End Sub
    '#End Region

    '#Region "Them_VaoPhieuNhap"
    '    Private Sub dtgThuoc_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
    '        If e.KeyCode = Keys.Enter Then
    '            Try
    '                count += 1
    '                Dim frm As frmPhieuNX = CType(fCallPhieuNX, frmPhieuNX)
    '                frm.AddNhomHang(dtgThuoc.Rows(dtgThuoc.SelectedCells(0).RowIndex).Cells("mathuoc").Value, count)
    '            Catch ex As Exception

    '            End Try
    '        ElseIf e.KeyCode = Keys.Escape Then
    '            Me.Close()
    '        End If
    '    End Sub

    '    Private Sub lbxKetQua_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
    '        If (e.KeyCode = Keys.Enter) Then
    '            Try
    '                count += 1
    '                Dim frm As frmPhieuNX = CType(fCallPhieuNX, frmPhieuNX)
    '                'frm.AddNhomHang(dtgThuoc.Rows(dtgThuoc.SelectedCells(0).RowIndex).Cells("mathuoc").Value, count)
    '                frm.AddNhomHang(CType(lbxKetQua.SelectedItem, CThuoc).MaThuoc, count)
    '            Catch ex As Exception

    '            End Try
    '        End If
    '    End Sub

    '    Private Sub lbxKetQua_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs)
    '        Try
    '            count += 1
    '            Dim frm As frmPhieuNX = CType(fCallPhieuNX, frmPhieuNX)
    '            'frm.AddNhomHang(dtgThuoc.Rows(dtgThuoc.SelectedCells(0).RowIndex).Cells("mathuoc").Value, count)
    '            frm.AddNhomHang(CType(lbxKetQua.SelectedItem, CThuoc).MaThuoc, count)
    '        Catch ex As Exception

    '        End Try
    '    End Sub
    '#End Region
    '#End Region

#End Region

#Region "Tab DM THUOC,TRANG BI, DUNG CU"
    Dim daThuoc As SqlDataAdapter
    Dim dsThuoc, dsLoaiThuoc As DataSet

    Dim flagthem As Boolean = False
    Dim flagsua As Boolean = False

    Public ma_cha As String = ""
    Const CtrlMask As Byte = 8

#Region "Load dsThuoc & dsLoaiThuoc"
    Public Sub LoadDMLoaiThuoc()
        Dim strSQl As String = "select * from tblLoaiThuoc"
        dsLoaiThuoc = BaseDB.ExecSql_DataSet(strSQl)
    End Sub

    Public Sub LoaddsThuoc()
        dsThuoc = BaseDB.ExecSql_DataSet("select * from tblDMTHUOC")
    End Sub
#End Region

#Region "tvThuoc"
    Public Sub KhoiTao_tvDMThuoc()
        'cho chon tat ca cac mat hang.(yeu cau)

        Dim node As TreeNode
        node = tvThuoc.Nodes.Add("KHO 706")

        'cu~ chon T or HC or BB cho hien T + HC + BB
        'If (ma_cha <> "") Then
        '    '"Y0500000000000"
        '    Dim strLoc As String
        '    If (ma_cha <> "Y0500000000000") And (ma_cha <> "Y0600000000000") And (ma_cha <> "Y0700000000000") Then
        '        strLoc = "ma_loaithuoc ='" & ma_cha & "'"
        '    Else
        '        strLoc = "ma_loaithuoc ='Y0500000000000' or ma_loaithuoc ='Y0600000000000' or ma_loaithuoc ='Y0700000000000'"
        '    End If
        '    Dim adr() As DataRow
        '    adr = dsLoaiThuoc.Tables(0).Select(strLoc)
        '    Dim row As DataRow
        '    For Each row In adr
        '        Dim childNode As TreeNode = node.Nodes.Add(row("ten_loaithuoc"))
        '        tvThuoc.SelectedNode = childNode
        '    Next
        'End If
    End Sub

    Private Sub tvThuoc_AfterSelect(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles tvThuoc.AfterSelect
        'AddChildCurrentNode()
        If (tvThuoc.SelectedNode.GetNodeCount(False) = 0) Then
            AddChildNode(CLoaiThuocs.GetLoaiThuocByTen(tvThuoc.SelectedNode.Text).MaLoaiThuoc)
            'sau khi them ma van khong co nut con 
            'y noi la nut la
            If (tvThuoc.SelectedNode.GetNodeCount(False) = 0) Then
                'KhoiTaodtgThuoc(CLoaiThuocs.GetLoaiThuocByTen(tvThuoc.SelectedNode.Text).MaLoaiThuoc)
                ''''''thay datagrid bang listview
                KhoiTaoLvThuoc(CLoaiThuocs.GetLoaiThuocByTen(tvThuoc.SelectedNode.Text).MaLoaiThuoc)
            Else
                'dtgThuoc.DataSource = Nothing
                lvThuoc.Items.Clear()
            End If
        Else
            'dtgThuoc.DataSource = Nothing
        End If
    End Sub

    Public Sub AddChildNode(ByVal macha As String)
        Dim strLoc As String
        strLoc = "ma_cha ='" & macha & "'"
        Dim adr() As DataRow
        adr = dsLoaiThuoc.Tables(0).Select(strLoc)
        Dim row As DataRow
        For Each row In adr
            tvThuoc.SelectedNode.Nodes.Add(row("ten_loaithuoc"))
        Next
    End Sub

    Public Sub RefreshCurrentNode()
        LoadDMLoaiThuoc()
        Dim node As TreeNode
        node = tvThuoc.SelectedNode
        node.Nodes.Clear()
        AddChildNode(CLoaiThuocs.GetLoaiThuocByTen(node.Text).MaLoaiThuoc)
    End Sub
#End Region

#Region "LvThuoc"
    Public Sub KhoiTaoLvThuoc(ByVal loaichaID As String, Optional ByVal selectedItem As String = "")
        lvThuoc.Items.Clear()
        Dim aryThuoc As ArrayList
        aryThuoc = CThuocs.GetThuocListByLoaiChaID(loaichaID)
        Dim item As ListViewItem
        For Each objThuoc As CThuoc In aryThuoc
            item = New ListViewItem(objThuoc.MaThuoc)
            item.SubItems.Add(objThuoc.TenThuoc)
            item.SubItems.Add(objThuoc.DonViTinh)
            lvThuoc.Items.Add(item)
        Next
        If selectedItem <> "" Then
            lvThuoc.SelectedItems(selectedItem).Selected = True
        End If
    End Sub
#End Region

#Region "dtgThuoc"
    'Public Sub KhoiTaodtgThuoc(ByVal loaichaID As String)
    '    Dim dv As DataView = New DataView(dsThuoc.Tables(0))
    '    dv.RowFilter = " MaLoaiThuoc = '" & loaichaID & "'"
    '    dtgThuoc.DataSource = dv
    '    FormatGridStyleThuoc()
    'End Sub

    'Public Sub FormatGridStyleThuoc()
    '    With dtgThuoc
    '        'Rename(HeaderText)
    '        With .Columns.Item("mathuoc")
    '            .HeaderText = "Mã Thuốc"
    '            .Width = 100
    '        End With
    '        With .Columns.Item("tenthuoc")
    '            .HeaderText = "Tên Thuốc"
    '            .Width = 300
    '        End With
    '        With .Columns.Item("maloaithuoc")
    '            .HeaderText = ""
    '            .ReadOnly = True
    '            .Visible = False
    '        End With
    '        With .Columns.Item("donvitinh")
    '            .HeaderText = "ĐVT"
    '            .Width = 75
    '        End With
    '    End With
    'End Sub
#End Region

#Region "btn Them, Xoa, Sua, Ghi, Huy"
    Private Sub btnThem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThem.Click
        If tvThuoc.SelectedNode.Nodes.Count() = 0 Then
            Dim frm As New frmNhapThuoc(CLoaiThuocs.GetLoaiThuocByTen(tvThuoc.SelectedNode.Text).MaLoaiThuoc, True)
            frm.fCallVattu = Me
            frm.ShowDialog()
        End If
    End Sub

    Private Sub btnThoat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThoat.Click
        Me.Close()
    End Sub

    Private Sub btnSua_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSua.Click
        If tvThuoc.SelectedNode.Nodes.Count() = 0 Then
            Dim frm As New frmNhapThuoc(lvThuoc.SelectedItems.Item(0).Text, False)
            frm.fCallVattu = Me
            frm.ShowDialog()
        End If
    End Sub

    Private Sub lvThuoc_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles lvThuoc.DoubleClick
        Try
            If fCallPhieuNX IsNot Nothing Then
                count += 1
                Dim frm As frmPhieuNX = CType(fCallPhieuNX, frmPhieuNX)
                frm.AddNhomHang(lvThuoc.SelectedItems(0).Text, count)
            End If
        Catch ex As Exception
            ShowMessages("Error: frmVattu dtgThuoc_CellDoubleClick: " + ex.ToString())
        End Try
    End Sub

    Private Sub lvThuoc_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles lvThuoc.KeyDown
        If e.KeyCode = Keys.Enter Then
            lvThuoc_DoubleClick(Nothing, Nothing)
        ElseIf e.KeyCode = Keys.Escape Then
            Me.Close()
        End If
    End Sub

    Private Sub btnTim_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) _
    Handles btnTim.KeyDown, btnXoa.KeyDown, btnCloseKetQua.KeyDown, btnIn.KeyDown, btnThem.KeyDown, btnSua.KeyDown, btnThoat.KeyDown, _
        lvDMMatHang.KeyDown, lbxKetQua.KeyDown
        If e.KeyCode = Keys.Escape Then
            Me.Close()
        End If
    End Sub

    Private Sub btnXoa_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnXoa.Click
        If (tvThuoc.SelectedNode.Nodes.Count() = 0) Then
            'kiem tra trong ton co loai thuoc nay hay chua? moi duoc xoa
            Dim mathuoc As String
            mathuoc = lvThuoc.SelectedItems.Item(0).Text
            Dim str As String
            str = "select count(*) from tblTon where ma = '" & mathuoc & "'"
            If (BaseDB.ExecSql_DataValue(str) <> 0) Then
                ShowMessages("Mã thuốc này tồn tại trong bảng Tồn,bạn phải xóa trong Tồn trước.")
                Exit Sub
            End If
            If (MsgBox("Bạn có muốn xóa loại thuốc này không?", MsgBoxStyle.YesNo, "CHÚ Ý")) = MsgBoxResult.Yes Then
                CThuocs.DeleteThuoc(CThuocs.GetThuocByMa(mathuoc))
                KhoiTaoLvThuoc(CLoaiThuocs.GetLoaiThuocByTen(tvThuoc.SelectedNode.Text).MaLoaiThuoc)
            End If
        End If
    End Sub

#End Region

#Region "btnTim"
    Private Sub btnTim_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTim.Click
        Dim tenthuoc As String
        Dim frm As New frmTimKiem
        frm.ShowDialog()
        tenthuoc = frm.txtGiaTri.Text
        If (tenthuoc.Trim <> "") Then
            lbxKetQua.Focus()
            KhoiTaolbxKetQua(tenthuoc)
            If (lbxKetQua.Items.Count <> 0) Then
                Panel3.Height = 150
                Panel3.Visible = True
                lbxKetQua.SelectedIndex = 0
                lbxKetQua.Focus()
            Else
                ShowMessages("Không tìm thấy")
            End If
        Else
            ShowMessages("Bạn chưa nhập tên thuốc cần tìm")
        End If
    End Sub

    Public Sub KhoiTaolbxKetQua(ByVal tenthuoc As String)
        Dim aryThuoc As ArrayList
        aryThuoc = CThuocs.GetThuocListByTen(tenthuoc)
        lbxKetQua.Items.Clear()
        For Each objThuoc As CThuoc In aryThuoc
            lbxKetQua.Items.Add(objThuoc)
        Next
    End Sub

    Private Sub lbxKetQua_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles lbxKetQua.DrawItem
        Try
            Dim brText As Brush
            If (e.State And DrawItemState.Selected) = DrawItemState.Selected Then
                brText = Brushes.White
            Else
                brText = Brushes.Black
            End If
            e.DrawBackground()
            Dim objThuoc As CThuoc = lbxKetQua.Items(e.Index)  'Me.lstItems.SelectedItem
            e.Graphics.DrawString(objThuoc.TenThuoc + " - " + objThuoc.DonViTinh, Me.lbxKetQua.Font, brText, e.Bounds.X + 5, e.Bounds.Y)
            e.DrawFocusRectangle()
        Catch ex As Exception
        Finally
        End Try
    End Sub

    Private Sub lbxKetQua_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lbxKetQua.SelectedIndexChanged
        'chon loai thuoc ben treeview loai thuoc
        'chon ten thuoc ben dtgDMThuoc

        If (lbxKetQua.SelectedIndex <> -1) Then
            Dim mathuoc, maloaithuoc As String
            Dim objThuoc As CThuoc
            objThuoc = CType(lbxKetQua.SelectedItem, CThuoc)
            mathuoc = objThuoc.MaThuoc
            maloaithuoc = objThuoc.MaLoaiThuoc

            'chon loai thuoc ben treeview loaithuoc
            ' tao ary chua tat ca cac cha cua loaithuoc dang tim
            Dim ary As New ArrayList
            Dim objLoaiThuoc As CLoaiThuoc
            Dim maloaithuoccha As String
            maloaithuoccha = maloaithuoc
            While (maloaithuoccha <> "Y0000000000000")
                'se bi lap neu tim khong thay
                objLoaiThuoc = CLoaiThuocs.GetLoaiThuocByMa(maloaithuoccha)
                If (objLoaiThuoc.MaLoaiThuoc Is Nothing) Then
                    ShowMessages("Loại thuốc này có mã không phù hợp")
                    Exit Sub
                End If
                ary.Add(objLoaiThuoc)
                maloaithuoccha = objLoaiThuoc.MaCha
            End While

            Dim node As TreeNode
            'default value is root
            node = tvThuoc.Nodes.Item(0)

            For i As Integer = 0 To ary.Count - 1
                objLoaiThuoc = ary.Item(ary.Count - i - 1)
                ' kiem tra xem node hien hanh co con khong neu chua thi add vao
                If (node.GetNodeCount(False) = 0) Then
                    'insert 
                    Dim aryLoaiThuocCon As ArrayList
                    aryLoaiThuocCon = CThuocs.GetThuocListByLoaiChaID(objLoaiThuoc.MaLoaiThuoc)
                    For Each obj As CLoaiThuoc In aryLoaiThuocCon
                        node.Nodes.Add(obj.TenLoaiThuoc)
                    Next
                End If
                'chon node tiep theo co ten trung voi objloaithuoc
                Dim n As TreeNode
                For Each n In node.Nodes
                    If (n.Text = objLoaiThuoc.TenLoaiThuoc) Then
                        node = n
                        tvThuoc.SelectedNode = node
                        node.ExpandAll()
                        Exit For
                    End If
                Next
            Next
            tvThuoc.SelectedNode = node
            KhoiTaoLvThuoc(maloaithuoc)

            'chon ten thuoc ben lvThuoc
            lvThuoc.Focus()
            For i As Integer = 0 To lvThuoc.Items.Count - 1
                If (lvThuoc.Items(i).SubItems(0).Text = mathuoc) Then
                    lvThuoc.Items(i).Selected = True
                    Exit For
                End If
            Next
            'set focus lai cho lbxKetQua
            lbxKetQua.Focus()
        End If
    End Sub

    Private Sub btnCloseKetQua_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCloseKetQua.Click
        Panel3.Height = 0
        Panel3.Visible = False
    End Sub
#End Region

#Region "Menu Them,Xoa,Sua LoaiThuoc"
    Private Sub XóaToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles XóaToolStripMenuItem.Click
        'kiem tra co node con hay khong? neu la node cuoi thi kiem tra co thuoc nao ko?
        Dim strLoc, maloaithuoc As String
        maloaithuoc = CLoaiThuocs.GetLoaiThuocByTen(tvThuoc.SelectedNode.Text).MaLoaiThuoc
        strLoc = "ma_cha ='" & maloaithuoc & "'"
        Dim adr() As DataRow
        adr = dsLoaiThuoc.Tables(0).Select(strLoc)
        If (adr.Length <> 0) Then
            ShowMessages("Bạn phải xóa các nhóm thuốc con trước khi muốn xóa nhóm thuốc này")
            Exit Sub
        Else ' day la node la.
            'kiem tra xem trong no co thuoc nao hay ko?
            strLoc = "MaLoaiThuoc ='" & maloaithuoc & "'"
            adr = dsThuoc.Tables(0).Select(strLoc)
            If (adr.Length <> 0) Then
                ShowMessages("Bạn phải xóa các thuốc con trước khi xóa nhóm thuốc này ")
                Exit Sub
            End If
        End If
        CLoaiThuocs.DeleteLoaiThuoc(CLoaiThuocs.GetLoaiThuocByTen(tvThuoc.SelectedNode.Text))
        tvThuoc.SelectedNode.Remove()
    End Sub

    Private Sub ThêmToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ThêmToolStripMenuItem.Click
        'cap nhat
        Dim frm As New frmNhapLoaiThuoc(CLoaiThuocs.GetLoaiThuocByTen(tvThuoc.SelectedNode.Text))
        frm.fCallVattu = Me
        frm.ShowDialog()
    End Sub
#End Region

#Region "In"
    Private Sub btnIn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnIn.Click
        Dim ma_loaithuoc As String = ""
        ma_loaithuoc = CLoaiThuocs.GetLoaiThuocByTen(tvThuoc.SelectedNode.Text).MaLoaiThuoc
        Dim str As String
        str = "delete tblDMThuoc_LoaiThuoc"
        BaseDB.ExecSql_NoneQuery(str)
        '
        KhoiTaoLoaiThuoc(ma_loaithuoc, 1)
        '
        Dim nnreport As New rptDMThuoc
        Dim ds As DataSet
        ds = BaseDB.ExecSql_DataSet("select * from tblDMThuoc_LoaiThuoc order by ma")
        nnreport.SetDataSource(ds.Tables(0))
        Dim frm As New frmReportViewer(nnreport)
        frm.ShowDialog()
    End Sub

    Public Sub KhoiTaoLoaiThuoc(ByVal ma_loaithuoc As String, ByVal level As Integer)
        'dieu kien dung: neu loai thuoc do la node la thi dung
        Dim aryLT As ArrayList = CLoaiThuocs.GetLoaiThuocListByMaCha(ma_loaithuoc)
        If (aryLT.Count = 0) Then
            Dim aryT As ArrayList = CThuocs.GetThuocListByLoaiChaID(ma_loaithuoc)
            For Each obj As CThuoc In aryT
                InsertThuoc_LoaiThuoc(obj.MaThuoc, 0, obj.MaThuoc, obj.TenThuoc, obj.DonViTinh, 0)
            Next
            'day la nut la.
            'insert Thuoc vao tblDMThuoc_LoaiThuoc voi ma_loaithuoc nhu tren
            Return
        End If

        For Each obj As CLoaiThuoc In aryLT
            'insert vao tblDMThuoc_LoaiThuoc
            InsertThuoc_LoaiThuoc(obj.MaLoaiThuoc, 1, obj.MaLoaiThuoc, obj.TenLoaiThuoc, "", level)
            KhoiTaoLoaiThuoc(obj.MaLoaiThuoc, level + 1)
        Next
    End Sub

    Public Function InsertThuoc_LoaiThuoc(ByVal ma As String, ByVal loai As Integer, ByVal mathuoc_loaithuoc As String, ByVal ten As String, ByVal dvt As String, ByVal cap As Integer) As Long
        Dim objConnection As IADOConnection = g_objConnFactory.GetConnection
        Dim objDBUtility As IDBUtility = objConnection.DBUtility
        'mathuoc, tenthuoc,maloaithuoc,donvitinh,ghichu

        'Dim sInsert As String = objStringBuilder.ToString
        Dim sInsert As String = "INSERT INTO tblDMThuoc_LoaiThuoc" & _
        " (ma,loai,mathuoc_loaithuoc,ten,dvt,cap) VALUES(" & _
        objDBUtility.GetParamPlaceHolder("Ma", True) & _
        objDBUtility.GetParamPlaceHolder("Loai", True) & _
        objDBUtility.GetParamPlaceHolder("MaThuoc_LoaiThuoc", True) & _
        objDBUtility.GetParamPlaceHolder("Ten", True) & _
        objDBUtility.GetParamPlaceHolder("DonViTinh", True) & _
        objDBUtility.GetParamPlaceHolder("Cap", False) & _
        ")"

        Dim objCommand As IDbCommand = objConnection.CreateCommand(sInsert)
        Dim objTransaction As IDbTransaction = objConnection.BeginTransaction
        Dim lRowsAffected As Long = 0

        Try
            With objCommand
                .Transaction = objTransaction
                .Parameters.Add(objDBUtility.CreateParameter("Ma", DbType.String, ma, ma.Length))
                .Parameters.Add(objDBUtility.CreateParameter("Loai", DbType.Int32, loai, 0))
                .Parameters.Add(objDBUtility.CreateParameter("MaThuoc_LoaiThuoc", DbType.String, mathuoc_loaithuoc, mathuoc_loaithuoc.Length))
                .Parameters.Add(objDBUtility.CreateParameter("Ten", DbType.String, ten, ten.Length))
                .Parameters.Add(objDBUtility.CreateParameter("DonViTinh", DbType.String, dvt, dvt.Length))
                .Parameters.Add(objDBUtility.CreateParameter("Cap", DbType.Int32, cap, 0))
                'Call objDBUtility.Prepare(objCommand)
                lRowsAffected = .ExecuteNonQuery()

            End With

            'lSerialKey = objDBUtility.InsertAndReturnSerialKey(objCommand, "DoiTuong_ID", "DoiTuong")
            objTransaction.Commit()

        Catch ex As System.Exception
            'MsgBox(ex.Message + ex.Source)
            objTransaction.Rollback()
            'Throw ex
        Finally
            objConnection.Close()
        End Try

        Return lRowsAffected
    End Function
#End Region

#Region "tvThuoc DrapDrop"
    Private Sub tvThuoc_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles tvThuoc.DragDrop
        Dim OriginationItem As ListViewItem = CType(e.Data.GetData("System.Windows.Forms.ListViewItem"), ListViewItem)
        'MsgBox(OriginationItem.SubItems(0).Text)
        If e.Data.GetDataPresent("System.Windows.Forms.ListViewItem", False) Then
            Dim pt As Point
            Dim DestinationNode As TreeNode
            pt = CType(sender, TreeView).PointToClient(New Point(e.X, e.Y))
            DestinationNode = CType(sender, TreeView).GetNodeAt(pt.X, pt.Y)
            '
            ''kiem tra xem co phai la node la ko? neu ko phai ko cho them vao.
            Dim str As String
            str = "select count(*) from tblLoaiThuoc where ma_cha = '" & CLoaiThuocs.GetLoaiThuocByTen(DestinationNode.Text).MaLoaiThuoc & "'"
            If (BaseDB.ExecSql_DataValue(str) <> 0) Then
                ShowMessages("Bạn không được chuyển vào Loại Thuốc " + DestinationNode.Text)
                Exit Sub
            End If
            '
            If (MsgBox("Bạn có muốn chuyển " + OriginationItem.SubItems(1).Text + " sang loại thuốc " + DestinationNode.Text, MsgBoxStyle.YesNo, "Chú ý") = MsgBoxResult.Yes) Then
                '
                'update MaLoaiThuoc cho thuoc can doi nhom.
                Dim objT As CThuoc
                objT = CThuocs.GetThuocByMa(OriginationItem.SubItems(0).Text)
                objT.MaLoaiThuoc = CLoaiThuocs.GetLoaiThuocByTen(DestinationNode.Text).MaLoaiThuoc
                CThuocs.UpdateThuoc(objT)
                'refesh
                KhoiTaoLvThuoc(CLoaiThuocs.GetLoaiThuocByTen(tvThuoc.SelectedNode.Text).MaLoaiThuoc)
            End If
        End If
    End Sub

    Private Sub tvThuoc_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles tvThuoc.DragEnter
        If (e.Data.GetDataPresent("System.Windows.Forms.ListViewItem")) Then
            If (e.KeyState And CtrlMask) = CtrlMask Then
                e.Effect = DragDropEffects.Copy
            Else
                e.Effect = DragDropEffects.Move
            End If
        Else
            e.Effect = DragDropEffects.None
        End If
    End Sub

    Private Sub tvThuoc_DragOver(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles tvThuoc.DragOver
        If (e.Data.GetDataPresent("System.Windows.Forms.ListViewItem")) Then
            If (e.KeyState And CtrlMask) = CtrlMask Then
                e.Effect = DragDropEffects.Copy
            Else
                'Dim DestinationNode As TreeNode
                'DestinationNode = CType(sender, TreeView).GetNodeAt(e.X, e.Y)
                ''kiem tra xem co phai la node la ko? neu ko phai ko cho them vao.
                'Dim str As String
                'str = "select count(*) from tblLoaiThuoc where ma_cha = '" & CLoaiThuocs.GetLoaiThuocByTen(DestinationNode.Text).MaLoaiThuoc & "'"
                'If (BaseDB.ExecSql_DataValue(str) <> 0) Then
                '    e.Effect = DragDropEffects.None
                'Else
                e.Effect = DragDropEffects.Move
                'End If
            End If
        Else
            e.Effect = DragDropEffects.None
        End If
    End Sub
#End Region

#Region "ListView DrapDrop"
    Private Sub lvThuoc_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles lvThuoc.DragEnter
        If (e.Data.GetDataPresent("System.Windows.Forms.ListViewItem")) Then
            If (e.KeyState And CtrlMask) = CtrlMask Then
                e.Effect = DragDropEffects.Copy
            Else
                e.Effect = DragDropEffects.Move
            End If
        Else
            e.Effect = DragDropEffects.None
        End If
    End Sub

    Private Sub lvThuoc_DragOver(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles lvThuoc.DragOver
        If (e.Data.GetDataPresent("System.Windows.Forms.ListViewItem")) Then
            If (e.KeyState And CtrlMask) = CtrlMask Then
                e.Effect = DragDropEffects.Copy
            Else
                e.Effect = DragDropEffects.Move
            End If
        Else
            e.Effect = DragDropEffects.None
        End If
    End Sub

    Private Sub lvThuoc_ItemDrag(ByVal sender As Object, ByVal e As System.Windows.Forms.ItemDragEventArgs) Handles lvThuoc.ItemDrag
        If e.Button = Windows.Forms.MouseButtons.Left Then
            DoDragDrop(e.Item, DragDropEffects.Move Or DragDropEffects.Copy)
        End If
    End Sub
#End Region

    '#Region "Them Vao Phieu Nhap"
    '    Private Sub dtgThuoc_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
    '        If e.KeyCode = Keys.Enter Then
    '            Try
    '                count += 1
    '                Dim frm As frmPhieuNX = CType(fCallPhieuNX, frmPhieuNX)
    '                frm.AddNhomHang(lvThuoc.SelectedItems.Item(0).Text, count)
    '            Catch ex As Exception

    '            End Try
    '        ElseIf e.KeyCode = Keys.Escape Then
    '            Me.Close()
    '        End If
    '    End Sub

    '    Private Sub lbxKetQua_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
    '        If (e.KeyCode = Keys.Enter) Then
    '            Try
    '                count += 1
    '                Dim frm As frmPhieuNX = CType(fCallPhieuNX, frmPhieuNX)
    '                'frm.AddNhomHang(dtgThuoc.Rows(dtgThuoc.SelectedCells(0).RowIndex).Cells("mathuoc").Value, count)
    '                frm.AddNhomHang(CType(lbxKetQua.SelectedItem, CThuoc).MaThuoc, count)
    '            Catch ex As Exception

    '            End Try
    '        End If
    '    End Sub

    '    Private Sub lbxKetQua_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs)
    '        Try
    '            count += 1
    '            Dim frm As frmPhieuNX = CType(fCallPhieuNX, frmPhieuNX)
    '            'frm.AddNhomHang(dtgThuoc.Rows(dtgThuoc.SelectedCells(0).RowIndex).Cells("mathuoc").Value, count)
    '            frm.AddNhomHang(CType(lbxKetQua.SelectedItem, CThuoc).MaThuoc, count)
    '        Catch ex As Exception

    '        End Try
    '    End Sub
    '#End Region

#End Region

#Region "DM LOHANG"
    'dung de luu gia tri loc cua lo hang
    'sau do truyen vao form Loc 
    Dim obj_MatHang As CMatHang
    Private ma_loaikho As String
    Private ma_kho As String
    Private dpnx_id As Integer
    Private ngay As Date
    Private slndkkh As Double = Nothing
    Private slxdkkh As Double = Nothing
    Private sltonkh As Double = Nothing

    Private Sub lvDMMathang_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles lvDMMatHang.DoubleClick
        lblSLKH.Visible = True
        txtSLKH.Text = ""
        txtSLKH.Visible = True
        txtSLKH.Focus()
    End Sub

    Private Sub txtTen_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtTen.KeyDown
        If e.KeyCode = Keys.Escape Then
            Me.Close()
        End If
    End Sub

    Private Sub txtTen_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtTen.TextChanged
        Dim lvItem As ListViewItem
        lvItem = lvDMMatHang.FindItemWithText(txtTen.Text)
        If lvItem IsNot Nothing Then
            lvDMMatHang.Focus()
            lvItem.Selected = True
            lvItem.Focused = True
            lvItem.EnsureVisible()
            txtTen.Focus()
        End If
    End Sub

    Public Sub Init()
        Dim strWhere As String
        strWhere = "where lk = '" + ma_loaikho + "' and kho = '" + ma_kho + "' and ngtton <= '" + Format(ngay, "M/d/yyyy") + "'"
        Dim aryDTs As ArrayList = CMatHangs.GetMatHangList(strWhere)
        lvDMMatHang.Items.Clear()
        Dim item As ListViewItem
        For Each objMH As CMatHang In aryDTs
            item = New ListViewItem(objMH.Ten)
            item.SubItems.Add(objMH.Lo)
            item.SubItems.Add(objMH.HanSD)
            item.SubItems.Add(objMH.SLTonKH.ToString(FormatMoneyStyle()))
            item.SubItems.Add(objMH.MatHang_ID)
            lvDMMatHang.Items.Add(item)
        Next

        If lvDMMatHang.Items.Count > 0 Then
            lvDMMatHang.Focus()
            lvDMMatHang.Items(0).Selected = True
        Else
            lblMaCode.Text = ""
            lblTenHang.Text = ""
            lblLoHang.Text = ""
            lblCCL.Text = ""
            lblHSD.Text = ""
            lblDonGia.Text = ""
            lblDVT.Text = ""
            lblTonKH.Text = ""
        End If
    End Sub

    Public Sub AddMathang()
        If fCallPhieuNX IsNot Nothing Then
            If Not IsNothing(Me.lvDMMatHang.SelectedItems(0)) Then
                count += 1
                If fCallPhieuNX.Name Is frmPhieuNX.Name Then
                    Dim frm As frmPhieuNX = CType(fCallPhieuNX, frmPhieuNX)
                    frm.AddMatHang(obj_MatHang, Double.Parse(txtSLKH.Text), count)
                ElseIf fCallPhieuNX.Name Is frmPhieuNXNoiBo.Name Then
                    Dim frm As frmPhieuNXNoiBo = CType(fCallPhieuNX, frmPhieuNXNoiBo)
                    frm.AddMatHang(obj_MatHang, Double.Parse(txtSLKH.Text), count)
                ElseIf fCallPhieuNX.Name Is frmPhieuNXDCSS.Name Then
                    Dim frm As frmPhieuNXDCSS = CType(fCallPhieuNX, frmPhieuNXDCSS)
                    frm.AddMatHang(obj_MatHang, Double.Parse(txtSLKH.Text), count)
                End If
            End If
        End If
    End Sub

    Private Sub GroupBox3_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles GroupBox3.KeyDown
        If e.KeyCode = Keys.Escape Then
            Me.Close()
        End If
    End Sub

    Private Sub lvDMMatHang_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles lvDMMatHang.KeyDown
        If e.KeyCode = Keys.Enter Then
            lvDMMathang_DoubleClick(Nothing, Nothing)
        ElseIf e.KeyCode = Keys.Escape Then
            Me.Close()
        End If
    End Sub

    Private Sub lvDMMatHang_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lvDMMatHang.SelectedIndexChanged
        Try
            If lvDMMatHang.Items.Count > 0 Then
                obj_MatHang = CMatHangs.GetMatHangByMa(lvDMMatHang.SelectedItems(0).SubItems(4).Text)
                lblTenHang.Text = obj_MatHang.Ten
                lblMaCode.Text = obj_MatHang.Ma + "-" + obj_MatHang.Code
                lblLoHang.Text = obj_MatHang.Lo
                lblCCL.Text = obj_MatHang.H
                lblHSD.Text = obj_MatHang.HanSD
                lblNgTTon.Text = obj_MatHang.NgTTon.ToString(FormatDateStyle())
                lblDonGia.Text = obj_MatHang.Gle.ToString(FormatMoneyStyle())
                lblDVT.Text = obj_MatHang.DVT
                lblLoaiKho.Text = CDoiTuongs.GetDoiTuongByMa(enumDOITUONG.LOAIKHO, obj_MatHang.LK).Ten
                If obj_MatHang.SLKK11 > 0 Then
                    lblSLKK.Text = obj_MatHang.SLKK11.ToString(FormatQuantityStyle())
                Else
                    lblSLKK.Text = "0"
                End If

                If obj_MatHang.SLSS11 > 0 Then
                    lblSLSSDauNam.Text = obj_MatHang.SLSS11.ToString(FormatQuantityStyle())
                Else
                    lblSLSSDauNam.Text = "0"
                End If
                'Tinh slton den tu truoc den ngay = "ngay" la bao nhieu
                CMatHangs.GetSLTonDenNgay(dpnx_id, obj_MatHang.MatHang_ID, ngay, sltonkh, Nothing, slndkkh, slxdkkh)
                If sltonkh > 0 Then
                    lblTonKH.Text = sltonkh.ToString(FormatMoneyStyle()) 'obj_MatHang.SLTonKH.ToString(FormatQuantityStyle())
                Else
                    lblTonKH.Text = "0"
                End If

                If slndkkh > 0 Then
                    lblLuyTichNhapKH.Text = slndkkh.ToString(FormatMoneyStyle()) 'obj_MatHang.SLNDKKH.ToString(FormatQuantityStyle())
                Else
                    lblLuyTichNhapKH.Text = "0"
                End If

                If slxdkkh > 0 Then
                    lblLuyTichXuatKH.Text = slxdkkh.ToString(FormatMoneyStyle()) 'obj_MatHang.SLXDKKH.ToString(FormatQuantityStyle())
                Else
                    lblLuyTichXuatKH.Text = "0"
                End If
            End If
        Catch ex As Exception

        End Try
    End Sub

    Private Sub txtSLKH_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtSLKH.KeyDown
        If e.KeyCode = Keys.Enter Then
            If txtSLKH.Text = "" Then
                ShowMessages("Số lượng nhập chưa nhập.")
                Exit Sub
            End If
            Try
                Dim value As Double = Double.Parse(txtSLKH.Text)
            Catch ex As Exception
                ShowMessages("Số lượng nhập không hợp lệ.")
                Exit Sub
            End Try
            AddMathang()
            lblSLKH.Visible = False
            txtSLKH.Visible = False
            lvDMMatHang.Focus()
        ElseIf e.KeyCode = Keys.Escape Then
            lblSLKH.Visible = False
            txtSLKH.Visible = False
        End If
    End Sub
#End Region
End Class